package com.poetize.plus.service.impl;

import com.poetize.plus.entity.vo.UploadVO;
import com.poetize.plus.properties.QiNiuProperties;
import com.poetize.plus.service.QiNiuService;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author zuosy
 * @created 2024/4/1 9:18
 */
@Service
@RequiredArgsConstructor
public class QiNiuServiceImpl implements QiNiuService {

    private final UploadManager uploadManager;

    private final Auth auth;

    private final QiNiuProperties qiNiuProperties;

    @Override
    public UploadVO upload(MultipartFile file) {
        try {
            //文件字节
            byte[] fileBytes = file.getBytes();
            //文件名
            String filename = file.getOriginalFilename();
            //文件类型
            String contentType = file.getContentType();
            assert contentType != null;
            String mime = contentType.substring(contentType.indexOf("/") + 1);
            //七牛云上传token
            String uploadToken = auth.uploadToken(qiNiuProperties.getBucket());

            Response response = this.uploadManager.put(fileBytes, filename, uploadToken, getPutPolicy(),
                    mime, false);
            if (response.statusCode == 200) {
                return new UploadVO(
                        filename,
                        qiNiuProperties.getDownloadUrl()+ filename,
                        Integer.valueOf(String.valueOf(file.getSize())),
                        mime
                        );
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 定义七牛云上传的相关策略
     */
    private StringMap getPutPolicy() {
        StringMap stringMap = new StringMap();
        stringMap.put("returnBody",
                "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"width\":$(imageInfo.width), \"height\":${imageInfo.height}}");
        return stringMap;
    }
}
